package com.ai.util;

import cn.hutool.http.HttpRequest;
import com.ai.entity.dto.OpenAiRes;
import com.ai.entity.dto.OpenAiResp;
import com.ai.exception.AiException;
import com.ai.service.AiService;
import com.ai.service.CallService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 调用openai
 */
@Component
public class OpenAiUtil {


    private static CallService callService;

    @Autowired
    public void setCallService(CallService callService) {
        OpenAiUtil.callService = callService;
    }

    private static AiService aiService;

    @Autowired
    public void setCallService(AiService aiService) {
        OpenAiUtil.aiService = aiService;
    }


    public static String sendToOpenAi(String content,String itemName) {
        String url = "https://jianhai.openai.azure.com/openai/deployments/jianhaiGPT/chat/completions?api-version=2023-05-15";
        OpenAiRes openAiRes = new OpenAiRes();
        OpenAiRes.MessagesDTO messagesDTO = new OpenAiRes.MessagesDTO();
        messagesDTO.setContent(content);
        List<OpenAiRes.MessagesDTO> messagesDTOS = new ArrayList<>();
        messagesDTOS.add(messagesDTO);
        openAiRes.setMessages(messagesDTOS);
        String body = JSON.toJSONString(openAiRes);
        String result = "";
        try {
            String respOpenAi = HttpRequest.post(url)
                    .body(body)
                    .header("api-key", "0fdb7abba33645e3b39a7e0f53d98fa6")
                    .timeout(300000)
                    .execute().body();
            System.out.println("【原始返回值】"+respOpenAi);
            if (respOpenAi.contains("Requests to the Creates a completion for the chat message Operation under Azure OpenAI API version 2023-05-15 have exceeded call rate limit of your current OpenAI S0 pricing tier")) {
                System.out.println("=========================被限流，等待10秒===========================");
                Thread.sleep(10000);
                return sendToOpenAi(content,itemName);
            }
            if (respOpenAi.contains("This model's maximum context length is 8192 tokens")){
                callService.singleB1(itemName);
                callService.singleC(itemName);
            }
            OpenAiResp openAiResp = JSON.parseObject(respOpenAi, OpenAiResp.class);
            System.out.println("【OpenAI】:" + JSONObject.toJSONString(respOpenAi));
            result = openAiResp.getChoices().get(0).getMessage().getContent();
            System.out.println("【OpenAi结果返回】" + result);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("结果报错，直接跳过");
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new AiException("sleep error");
        }
        return result;
    }


}
